/*
 * @Author: lsjweiyi 759209794@qq.com
 * @Date: 2024-04-02 22:40:50
 * @LastEditors: lsjweiyi 759209794@qq.com
 * @LastEditTime: 2024-04-20 14:50:43
 * @FilePath: \web-ssg\utils\request.ts
 * @Description: 封装的http请求
 */
import { createDiscreteApi } from "naive-ui";
// 指定后端返回的基本数据类型
export interface IResponse<T> {
    logId: string;
    data?: T;
    code: number;
    taskId: string;
    headers: Headers;
    downTimes?: number;
}
// <T, NitroFetchRequest, NitroFetchOptions<NitroFetchRequest, method>>
function fetch<T>(url: string, options?: any): Promise<IResponse<T>> {
    return $fetch<IResponse<T>>(url, {
        ...options,
        baseURL: baseUrlKey().value,
        retry: false,
        onResponse({ response }) {
            let contentType = response.headers.get("content-type");
            let logId = response.headers.get("Log-Id");
            let taskId = response.headers.get("task-id");
            // 请求码不为200等正常码的情况
            if (!response.ok) {
                response._data = { code: -1, data: "请求已到达服务器但未正常响应：" + response.statusText, logId: logId };
                return;
            }

            if (!contentType) {
                response._data = { code: -1, data: "返回数据不符合预期", logId: logId };
                return;
            } else if (contentType == "application/json; charset=utf-8") {
                response._data.logId = logId;
                response._data.taskId = taskId;
                response._data.headers = response.headers;
                return;
            } else {
                const disposition = response.headers.get("content-disposition");
                if (!disposition) {
                    response._data = { code: -1, data: "返回数据不符合预期", logId: logId };
                    return;
                }
                // 切割出文件名
                const blob = new Blob([response._data], { type: contentType });
                let urlObj = window.URL || window.webkitURL || window;
                const downUrl = urlObj.createObjectURL(blob);
                response._data = { code: 1, data: downUrl, taskId: taskId, headers: response.headers };
                return;
            }
        },
        onRequestError({ error }) {
            console.log(error);

            const { dialog } = createDiscreteApi(["dialog"]);
            dialog.error({
                title: "请求失败！",
                content: "请检查网络是否正常，刷新页面后重试或联系管理员：" + error.message,
                positiveText: "确定",
                onPositiveClick: () => { },
            });
        },
    }).catch((error) => {
        return error.data;
    });
}

export function get<T>(url: string, params?: any) {
    return fetch<T>(url, { method: "get", ...params });
}

export function post<T>(url: string, params?: any) {
    return fetch<T>(url, { method: "post", ...params });
}

// 利用a标签下载文件
export function aDown(url: string, taskId: string, toolId: number) {

    const dom = document.createElement("a");
    dom.href = baseUrlKey().value + url;
    dom.style.display = "none";
    document.body.appendChild(dom);
    dom.click();
    document.body.removeChild(dom);
    return new Promise<IResponse<string | number>>((resolve) => {
        setTimeout(() => {
            get<number | string>("downTimes", requestConfig(taskId, toolId)).then((res) => {
                resolve(res)
            })
        }, 2000)
    })

}